/* eslint-disable vue/no-template-shadow */
<template>
  <a-modal
    title="编辑用户"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-divider orientation="left">基本信息</a-divider>
      <a-row :gutter="24">

    <a-form :form="form">
        <a-form-item
          label="头像"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback=""
        >

          <a-upload
                :showUploadList="false"
                :accept="fileType"
                @change="handleChange"
                :multiple="false"
                :file-list="msgUrl"
                :remove="handleRemove"
                :customRequest="customRequest"
                v-decorator="['avatar', {rules: [{ required: true, message: '请选择头像！' }]}]"
               >
               <div>
                 <a-button> <a-icon type="upload" /> 上传图片 </a-button>

                </div>
            </a-upload>
            <div  style="display: flex;justify-content: flex-start;width: 100px;position: relative;" v-if="form.getFieldValue('avatar')">
                <img :src="$util.formatImageUrl(form.getFieldValue('avatar'))"  alt="example" style="width: 100px;height: 100px;" />
                <div style="text-align: center;line-height: 20px;box-sizing: border-box; color: #FFFFFF;font-size: 20px;  width: 20px;height: 20px;border-radius: 50%; background: #000000;opacity: 0.6; position: absolute;z-index: 99;right: 0;top: 0;transform: translate(50%,-50%);">
                   <div style="right: 50%;top: 40%;transform: translate(50%,-50%);position: absolute;cursor:pointer;" @click="handleRemove">x</div>
                </div>
              </div>

        </a-form-item>
  </a-form>


        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['id']" />
            </a-form-item>
            <a-form-item
              label="账号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入账号" v-decorator="['account', {rules: [{required: true, min: 5, message: '请输入至少五个字符的账号！'}]}]" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24" >
          <a-form :form="form">
            <a-form-item
              label="姓名"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入姓名" v-decorator="['name', {rules: [{required: true, message: '请输入姓名！'}]}]" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="昵称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入昵称" v-decorator="['nickName']" />
            </a-form-item>
          </a-form>
        </a-col>
         <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="性别"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-radio-group v-decorator="['sex',{rules: [{ required: true, message: '请选择性别！' }]}]" >
                <a-radio :value="1">男</a-radio>
                <a-radio :value="2">女</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="手机号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入手机号" v-decorator="['phone',{rules: [{ required: true, message: '请输入手机号！' }]}]" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入电话" v-decorator="['tel']" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left">员工信息</a-divider>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="机构"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-tree-select
                v-decorator="['orgId', {rules: [{ required: true, message: '请选择机构！' }]}]"
                style="width: 100%"
                :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                :treeData="orgTree"
                placeholder="请选择机构"
                treeDefaultExpandAll
                @change="e => initrOrgName(e)"
              >
                <span slot="title" slot-scope="{ id }">{{ id }}</span>
              </a-tree-select>
            </a-form-item>
            <!--            <a-form-item v-show="false">-->
            <!--              <a-input v-decorator="['sysEmpParam.orgName']" />-->
            <!--            </a-form-item>-->
          </a-form>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>
<script>
  import { sysUserEdit, sysUserDetail } from '@/api/modular/system/userManage'
  import { getOrgTree, getOrgList } from '@/api/modular/system/orgManage'
  import { sysPosList } from '@/api/modular/system/posManage'
  import moment from 'moment'
  import {sysFileInfoUpload} from '@/api/modular/system/fileManage'
  import Vue from 'vue'
  import {ACCESS_TOKEN} from '@/store/mutation-types'
  export default {
    data () {
      return {
        fileType:'',
        msgUrl:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        // 机构行样式
        labelCol_JG: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol_JG: {
          xs: { span: 24 },
          sm: { span: 20 }
        },
        count: 1,
        columns: [
          {
            title: '附属机构',
            dataIndex: 'extOrgId',
            width: '45%',
            scopedSlots: { customRender: 'extOrgId' }
          },
          {
            title: '附属岗位',
            dataIndex: 'extPosId',
            width: '45%',
            scopedSlots: { customRender: 'extPosId' }
          },
          {
            title: '操作',
            key: 'action',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        visible: false,
        confirmLoading: false,
        orgTree: [],
        orgList: [],
        posList: [],
        sysEmpParamExtList: [],
        memberLoading: false,
        form: this.$form.createForm(this),
        data: [],
        birthdayString: ''
      }
    },
    methods: {
     handleRemove() {
       setTimeout(() => {
         this.form.setFieldsValue({
           avatar:'',

         })
        }, 100)
       this.msgUrl=[]
     },


      customRequest (data) {
        this.confirmLoading = true
        const formData = new FormData()
        formData.append('file', data.file)
        sysFileInfoUpload(formData).then((res) => {
          if (res.success) {
            console.log(res.data)
             data.onSuccess(res, data.file)
             this.form.setFieldsValue({
                 avatar:res.data,
             })
             this.confirmLoading = false
             this.$message.success('上传成功')
          } else {
             this.confirmLoading = false
            this.$message.error('上传失败：' + res.message)
          }
        })


        // const formData = new FormData()
        // formData.append('file', data.file)
        // sysFileInfoUpload(formData).then((res) => {
        //   if (res.success) {
        //     this.$message.success('上传成功')
        //
        //     const token = Vue.ls.get(ACCESS_TOKEN)
        //
        //     let _fl = this.fileList
        //     let lastFile = _fl[_fl.length - 1]
        //     let imageUrl = `${$store.state.baseUrl}/sysFileInfo/preview?id=${res.data}&token=${token}`
        //     // 为了节省流量，上传成功的图片预览图直接使用文件的thumbUrl
        //     imageUrl = lastFile.thumbUrl
        //     lastFile.fileID = res.data
        //     lastFile.url = imageUrl
        //     lastFile.status = 'done'
        //
        //     let image = _fl.map(value => value.fileID).join(',')
        //     this.form.setFieldsValue({image})
        //   } else {
        //     this.$message.error('上传失败：' + res.message)
        //   }
        // })

      },


      handleChange(file) {// 当多余一个的时候替换文件

          if (file.fileList.length > 1) {
            file.fileList.splice(0, 1)
          }
          let fileList = [...file.fileList]
          fileList = fileList.slice(-2)
          // 2. read from response and show file link
          fileList = fileList.map(file => {
            if (file.response) {
              // Component will show file.url as link
              file.url = file.response.url
            }
            return file
          })
          this.msgUrl = fileList
      },



      // 初始化方法
      edit (record) {
        this.confirmLoading = true
        this.visible = true
        this.getOrgData()

        // 基本信息加人表单
        setTimeout(() => {
          this.form.setFieldsValue(record)

          // this.form.setFieldsValue(
          //   {
          //     id: record.id,
          //     account: record.account,
          //     name: record.name,
          //     nickName: record.nickName,
          //     sex: record.sex,
          //     phone: record.phone,
          //     tel: record.tel,
          //     avatar:record.avatar,
          //     orgId:record.orgId
          //   }
          // )
        }, 100)
        // 时间单独处理
        if (record.birthday != null) {
          this.form.getFieldDecorator('birthday', { initialValue: moment(record.birthday, 'YYYY-MM-DD') })
        }
        this.birthdayString = moment(record.birthday).format('YYYY-MM-DD')
        // 职位信息加入表单
        this.getUserDetaile(record.id)
      },
      /**
       * 通过用户ID查询出用户详情，将职位信息填充
       * @param id
       */
      getUserDetaile (id) {
        sysUserDetail({ 'id': id }).then((res) => {
          const SysEmpInfo = res.data.sysEmpInfo
          const Positions = []
          SysEmpInfo.positions.forEach(item => {
            Positions.push(item.posId)
          })
          this.form.getFieldDecorator('sysEmpParam.orgName', { initialValue: SysEmpInfo.orgName })
          this.form.getFieldDecorator('sysEmpParam.posIdList', { initialValue: Positions })
          this.form.getFieldDecorator('sysEmpParam.jobNum', { initialValue: SysEmpInfo.jobNum })
          this.form.getFieldDecorator('sysEmpParam.orgId', { initialValue: SysEmpInfo.orgId })
          SysEmpInfo.extOrgPos.forEach(item => {
            const length = this.data.length
            this.data.push({
              key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
              extOrgId: item.orgId,
              extPosId: item.posId
            })
          })
          this.confirmLoading = false
        })
      },
      /**
       * 增行
       */
      newMember () {
        const length = this.data.length
        this.data.push({
          key: length === 0 ? '1' : (parseInt(this.data[length - 1].key) + 1).toString(),
          extOrgId: '',
          extPosId: ''
        })
      },
      /**
       * 删除
       */
      remove (key) {
        const newData = this.data.filter(item => item.key !== key)
        this.data = newData
      },
      /**
       * 选择子表单单项触发
       */

      /**
       * 获取机构数据，并加载于表单中
       */
      getOrgData () {
        getOrgTree().then((res) => {
          this.orgTree = res.data
        })
        getOrgList().then((res) => {
          this.orgList = res.data
        })
      },
      /**
       * 获取职位list列表
       */
      getPosList () {
        sysPosList().then((res) => {
          this.posList = res.data
        })
      },
      /**
       * 选择树机构，初始化机构名称于表单中
       */
      initrOrgName (value) {
        this.form.getFieldDecorator('sysEmpParam.orgName', { initialValue: this.orgList.find(item => value === item.id).name })
      },
      /**
       * 子表单json重构
       */
      JsonReconsitution () {
        this.sysEmpParamExtList = []
        const newData = [...this.data]
        newData.forEach(item => {
          // eslint-disable-next-line eqeqeq
          if (item.extOrgId != '' & item.extPosId != '') {
            this.sysEmpParamExtList.push({ orgId: item.extOrgId, posId: item.extPosId })
          }
        })
      },
      /**
       * 日期需单独转换
       */
      onChange (date, dateString) {
        this.birthdayString = moment(date).format('YYYY-MM-DD')
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            this.JsonReconsitution()
            // values.sysEmpParam['extIds'] = this.sysEmpParamExtList
            // eslint-disable-next-line eqeqeq
            if (this.birthdayString == 'Invalid date') {
              this.birthdayString = ''
            }
            values.birthday = this.birthdayString
            sysUserEdit(values).then((res) => {
              if (res.success) {
                this.$message.success('编辑成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error('编辑失败：' + res.message)
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.visible = false
        // 清理子表单中数据
        this.data = []
        // 清理时间
        this.birthdayString = ''
        this.form.getFieldDecorator('birthday', { initialValue: null })
      }
    }
  }
</script>
